package com.ms.mishitong.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.ms.mishitong.VO.UserVO;
import com.ms.mishitong.dto.Result;
import com.ms.mishitong.dto.UserDTO;
import com.ms.mishitong.entity.Follow;
import com.ms.mishitong.entity.PageResult;
import com.ms.mishitong.entity.User;
import com.ms.mishitong.mapper.FlowMapper;
import com.ms.mishitong.mapper.UserMapper;
import com.ms.mishitong.service.IFollowService;
import com.ms.mishitong.service.IUserService;
import com.ms.mishitong.utils.RedisConstants;
import com.ms.mishitong.utils.ThroadLocal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@Service
public class FollowServiceImpl extends ServiceImpl<FlowMapper, Follow> implements IFollowService {
    @Autowired
    private FlowMapper flowMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private IUserService userService;
    @Autowired
    private UserMapper userMapper;

    @Override
    public Result follow(Long id, Boolean isFollow) {

        Long userId = ThroadLocal.get().getId();
        Follow follow = new Follow();
        follow.setUserId(userId);
        follow.setFollowUserId(id);
        String key = RedisConstants.FOLLOW_KEY+userId;
         if(isFollow){

               save(follow);


                 stringRedisTemplate.opsForSet().add(key,id.toString());

         }
         else{

             flowMapper.Delete(follow);
             log.info("取消关注");
             stringRedisTemplate.opsForSet().remove(key,id.toString());
         }
         return Result.ok();
    }

    @Override
    public Result isFollow(Long id) {
        Long userId = ThroadLocal.get().getId();
        Follow follow = new Follow();
        follow.setUserId(userId);
        follow.setFollowUserId(id);
        if(flowMapper.Select(follow) != null){
            return Result.ok(true);
        }
        else{
            return Result.ok(false);
        }
    }

    @Override
    public Result followcommon(Long id) {
        Long userId = ThroadLocal.get().getId();
        String key1 = RedisConstants.FOLLOW_KEY+userId;
        String key2= RedisConstants.FOLLOW_KEY+id;
        Set<String> intersect = stringRedisTemplate.opsForSet().intersect(key1,key2);
        if(intersect == null|| intersect.isEmpty()){
            return Result.ok(Collections.emptyList());
        }
        List<Long> ids = intersect.stream().map(Long::valueOf).collect(Collectors.toList());
        List<UserDTO> users = userService.listByIds(ids)
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        return Result.ok(users);
    }

    @Override
    public List<User> getFollows(Long UserId) {
           List< Long> followIds = flowMapper.getFollows(UserId);
           List< User> users = null;
           if(!followIds.isEmpty()){
              users  = userService.listByIds(followIds);
           }
        return  users;
    }


    @Override
    public Result getMutual(Long cursor, int pageSize) {
        // 当前登录用户ID（从Token中获取）
        Long userId = ThroadLocal.get().getId();
        log.info("用户ID:{}",userId);
        // 1. 查询互关好友ID（基于游标分页）
        log.info("userId:{},pageSize:{}",userId,pageSize);
        List<Long> mutualList =  flowMapper.queryMutualByCursor(userId, cursor, pageSize);
        log.info("好友ID:{}",mutualList);
        List<UserVO> mutualListVO = null;
        if(mutualList.isEmpty()){
            return Result.ok(mutualListVO);
        }
          mutualListVO = userMapper.GetUserVO(mutualList);
        // 2. 计算是否还有更多数据
        boolean hasMore = false;
        Long nextCursor = null;
//        if (!mutualList.isEmpty()) {
//            // 新游标 = 当前页最后一条数据的id
//            nextCursor = mutualList.get(mutualList.size() - 1);
//            // 判断是否还有更多：查询是否存在比新游标小的id（即下一页是否有数据）
//            hasMore = hasMoreMutual(userId, nextCursor);
//        }
        log.info("好友；{}",mutualListVO);
        // 3. 封装结果返回
        return Result.ok(new PageResult(mutualListVO, nextCursor, hasMore));

    }

    @Override
    public List<Long> getFollowIds(Long UserId) {
         return flowMapper.getFollows(UserId);
    }

    private boolean hasMoreMutual(Long userId, Long cursor) {
        if(flowMapper.hasMoreMutual(userId, cursor) != null) {
            return true;
        }
        return false;
    }

}
